export function log(message: any): void {
    if (typeof message === "object") {
        message = JSON.stringify(message, null, 2);
    }
    console.log(message);
    console.log("\n");
}

export function show_trace(this: any): void {
    // 通过 Frida 来打印堆栈信息
    // Java.perform(function () {
    //     // var Exception = Java.use("java.lang.Exception");
    //     // // 实例化一个 Exception 对象
    //     // var ins = Exception.$new("Exception");
    //     // // 打印堆栈信息
    //     // console.log(ins.getStackTrace());

    // });

    console.log(
        Java.use("android.util.Log").getStackTraceString(
            Java.use("java.lang.Throwable").$new()
        )
    ); //java打印堆栈
}

var logContentArray = new Array();

var singlePrefix = "|----";

// trace a specific Java Method
export function traceMethod(targetClassMethod: string) {
    var delim = targetClassMethod.lastIndexOf(".");
    if (delim === -1) return;

    // slice() 方法可提取字符串的某个部分，并以新的字符串返回被提取的部分
    var targetClass = targetClassMethod.slice(0, delim);
    var targetMethod = targetClassMethod.slice(
        delim + 1,
        targetClassMethod.length
    );
    var hook = Java.use(targetClass);
    var overloadCount = hook[targetMethod].overloads.length;
    console.log(
        "Tracing " + targetClassMethod + " [" + overloadCount + " overload(s)]"
    );
    for (var i = 0; i < overloadCount; i++) {
        // hook方法
        hook[targetMethod].overloads[i].implementation = function () {
            var logContent_1 = "entered--" + targetClassMethod;

            var prefixStr = gainLogPrefix(logContentArray);

            logContentArray.push(prefixStr + logContent_1);

            console.warn(prefixStr + logContent_1);

            // print backtrace, 打印调用堆栈
            // Java.perform(function() {
            // 	var bt = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new());
            // 	console.log(prefixStr +"Backtrace:" + bt);
            // });

            // print args
            // if (arguments.length) console.log();

            // 打印参数
            for (var j = 0; j < arguments.length; j++) {
                var tmpLogStr = prefixStr + "arg[" + j + "]: " + arguments[j];
                console.log(tmpLogStr);
                logContentArray.push(tmpLogStr);
            }
            // print retval
            var retval = this[targetMethod].apply(this, arguments); // rare crash (Frida bug?)
            // 打印返回值
            // console.log("\n"+ targetClassMethod +"--retval: " + retval);
            var tmpReturnStr = prefixStr + "retval: " + retval;
            logContentArray.push(tmpReturnStr);
            console.log(tmpReturnStr);
            //结束标志
            var logContent_ex = "exiting--" + targetClassMethod;
            logContentArray.push(prefixStr + logContent_ex);
            console.warn(prefixStr + logContent_ex);
            return retval;
        };
    }
}

// 获取打印前缀
function gainLogPrefix(theArray: Array<string>) {
    var lastIndex = theArray.length - 1;

    if (lastIndex < 0) {
        return singlePrefix;
    }

    for (var i = lastIndex; i >= 0; i--) {
        var tmpLogContent = theArray[i];
        var cIndex = tmpLogContent.indexOf("entered--");

        if (cIndex == -1) {
            var cIndex2 = tmpLogContent.indexOf("exiting--");
            if (cIndex2 == -1) {
                continue;
            } else {
                //与上个方法平级
                var resultStr = tmpLogContent.slice(0, cIndex2);
                return resultStr;
            }
        } else {
            //在上个方法的内部
            var resultStr = singlePrefix + tmpLogContent.slice(0, cIndex); //replace(/entered--/, "");
            // console.log("("+tmpLogContent+")前缀是：("+resultStr+")");
            return resultStr;
        }
    }
    return "";
}

export function send_wx_text_toUser(msg: string, username: string) {
    Java.choose("com.tencent.mm.ui.chatting.r1", {
        onMatch: function (instance): any {
            // 调用前先hook
            let b = Java.use("nv3.b");
            b["r"].implementation = function () {
                // console.log(`b.r is called`);
                // let result = this["r"]();
                return username;
            };
            let result = instance.t(msg);
        },
        onComplete: function () {
            // 还原 hook
            let b = Java.use("nv3.b");
            b["r"].implementation = function () {
                return this["r"]();
            };
        },
    });
}


// 100 容量的数组
var msgIDArray = new Array(100);
// 插入msgID 如果count大于100则从头开始覆盖
function insertMsgID(msgID: number) {
    if (msgIDArray.length < 100) {
        msgIDArray.push(msgID);
    } else {
        msgIDArray.shift();
        msgIDArray.push(msgID);
    }
}
// 判断msgID是否存在
function isMsgIDExist(msgID: number) {
    return msgIDArray.includes(msgID);
}
// 判断是否是重复的消息
export function isRepeatMsg(msgID: number) {
    if (isMsgIDExist(msgID)) {
        return true;
    } else {
        insertMsgID(msgID);
        return false;
    }
}